import { Inject, Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, Timeout } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { RedisCacheService } from 'src/component/redis/redis-cache.service';
import { EssayEntity } from 'src/module/essay/entities/essay.entity';
import { EssayService } from 'src/module/essay/essay.service';
import { Repository } from 'typeorm/repository/Repository';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  @InjectRepository(EssayEntity)
  private readonly essayRepository: Repository<EssayEntity>;

  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private readonly redisService: RedisCacheService,
    private readonly essayService: EssayService,
  ) {}

  //   @Cron('45 * * * * *')
  //   handleCron() {
  //     this.logger.debug('该方法将在45秒标记处每分钟运行一次');
  //   }

  //   @Interval(10000)
  //   handleInterval() {
  //     this.logger.debug('2');
  //   }

  /**
   * 定时刷新浏览历史  五分钟刷一次
   */
  @Interval(1000 * 60 * 5)
  async refreshBrowsingHistory() {
    let cacheKey = /^essay_view_count_/;
    let ids = await this.redisService.getKeysByPattern(cacheKey);

    try {
      ids.forEach(async (id) => {
        let essayId = id.replace('essay_view_count_', '');
        let needAddCount = await this.redisService.get(id);
        let count = 0;

        const essay = await this.essayRepository
          .createQueryBuilder('essay')
          .where('essay.id = :id', { id: essayId })
          .select(['essay.view_count'])
          .getOne();

        count = essay.view_count + Number(needAddCount);

        this.logger.debug(`essay_id_${essayId}:${count}`);

        await this.essayRepository
          .createQueryBuilder('essay')
          .update(EssayEntity)
          .set({ view_count: count })
          .where('essay.id = :id', { id: essayId })
          .execute();

        // await this.essayService.update(essayId, {
        //   id: essayId,
        //   view_count: count,
        // });
        this.redisService.del(id);
      });

      this.logger.debug('浏览记录刷新成功');

      // 清除整个缓存
      await this.cacheManager.reset();
    } catch (error) {
      this.logger.debug('浏览记录刷新失败');
    }
  }
}
